#coding:utf-8

"""
11.10 ga1400, ctcp, hik 服务器软件界面
2021.4.13 解析json数据使用线程方式
2021.5.21 包括https GA1400
2021.7.26 增加Checkbutton 控制服务器是否要求刷新注册
"""
import tkinter as tk
from tkinter.messagebox import *
from tkinter import filedialog
import time
import os
import threading
import tcp_cpss_v2, http_Hik_v2, http_GA_v2,https_GA
import get_jsonkeys
import traverse_json
import json

tkVERSION = ' 11.0'
versionDate = ' 2021.7.26'
filename = os.path.basename(__file__)    
def print_tofile(*args):   # 打印日志
    return
    #msg = '[%s] '%os.path.split(__file__)[1]
    #msg = "[ppid=%d, pid=%d] "%(os.getppid(), os.getpid())
    msg = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()) + " [%s] "%filename
    for x in args:
        msg += str(x) + ' '
    logfilename = 'log_' + filename.split('.')[0] + '.log'
    with open(logfilename, 'a') as f:
        print(msg, file=f)
    print(msg)  
    
class PageOne(tk.Frame):
    title = 'Server' + tkVERSION + versionDate
    def __init__(self, parent, root):
        super().__init__(parent)
        root.protocol('WM_DELETE_WINDOW', self.closeWindow)
        self.ctcp = tcp_cpss_v2.Ctcp() 
        self.ctcp_t = threading.Thread(target=self.ctcp_run_thread, name='ctcp_run_thread')
        self.hik = http_Hik_v2.HIK() 
        self.hik_t = threading.Thread(target=self.hik_run_thread, name='hik_run_thread')
        self.ga = http_GA_v2.GA() 
        self.ga_t = threading.Thread(target=self.ga_run_thread, name='ga_run_thread')
        self.gahttps = https_GA.GAHttps() 
        self.gahttps_t = threading.Thread(target=self.gahttps_run_thread, name='gahttps_run_thread')
        self.query_t = threading.Thread(target=self.query_thread, name='query_thread')
        self.parse_t = threading.Thread(target=self.parse_thread, args=(0,),name='parse_thread')
        self._running = threading.Event()
        self._running.clear()
        print_tofile('start'.center(50, '-'))
        self.init_Window()   
        #root.bind('<F1>', self.funcFone)
        
    def closeWindow(self):
        if self.ga_t.is_alive():
            self.ga.stop()
        if self.gahttps_t.is_alive():
            self.gahttps.stop()
        if self.ctcp_t.is_alive():
            self.ctcp.stop()
        if self.hik_t.is_alive():
            self.hik.stop()
        self.quit()
        
    def funcFone(self, event):
        showinfo(title='帮助', message=self.ctcp.infomsg)    
        
    def init_Window(self):
        msg = self.title + '\n'
        msg += '1, 点击 “启用CTCP” “启用GA1400” “启用GA1400(https)” “启用HIK” 运行服务器\n'
        msg += '2, 点击 “查询” 查询收到的图片数量，前端IP可以用“;”分割或设置为空'
        tk.Label(self, text=msg, justify=tk.LEFT).grid(row=0, column=0, padx=2, pady=2, sticky=tk.W)
        self.init_Window_CTCP()
        self.init_Window_GA()
        self.init_Window_HIK()
        self.query_setting()
        
    def query_setting(self):    
        query_Frame = tk.LabelFrame(self, text='查询设置', padx=2, pady=2)
        query_Frame.grid(row=1, column=1, padx=15, pady=5, rowspan=10, stick=tk.W)   
        self.q_GA1400 = tk.IntVar()
        self.q_CTCP = tk.IntVar()
        self.q_HIK = tk.IntVar()
        self.q_GA1400.set(1)
        self.q_CTCP.set(1)
        self.q_HIK.set(1)    
        tk.Label(query_Frame, text='服务器类型:').grid(row=0, column=0, padx=2, pady=2, stick=tk.W)    
        tk.Checkbutton(query_Frame, text='GA1400', variable=self.q_GA1400).grid(row=0, column=1, padx=2, pady=2, sticky=tk.W)
        tk.Checkbutton(query_Frame, text='CTCP', variable=self.q_CTCP).grid(row=0, column=2, padx=2, pady=2, sticky=tk.W)
        tk.Checkbutton(query_Frame, text='HIK', variable=self.q_HIK).grid(row=0, column=3, padx=2, pady=2, sticky=tk.W)
        
        tk.Label(query_Frame, text='GA1400 POST类型:').grid(row=1, column=0, padx=2, pady=2, stick=tk.W)        
        self.Faces = tk.IntVar()
        self.Persons = tk.IntVar()
        self.MotorVehicles = tk.IntVar()
        self.NonMotorVehicles = tk.IntVar()
        self.Images = tk.IntVar()
        self.Files = tk.IntVar()
        self.VideoSlices = tk.IntVar()
        self.Faces.set(0)
        self.Persons.set(0)
        self.MotorVehicles.set(0)
        self.NonMotorVehicles.set(0)
        self.Images.set(0)
        self.Files.set(0)
        self.VideoSlices.set(0)              
        tk.Checkbutton(query_Frame, text='人脸', variable=self.Faces).grid(row=1, column=1, padx=2, pady=2, sticky=tk.W)
        tk.Checkbutton(query_Frame, text='人员', variable=self.Persons).grid(row=1, column=2, padx=2, pady=2, sticky=tk.W)
        tk.Checkbutton(query_Frame, text='机动车', variable=self.MotorVehicles).grid(row=1, column=3, padx=2, pady=2, sticky=tk.W)
        tk.Checkbutton(query_Frame, text='非机动车', variable=self.NonMotorVehicles).grid(row=1, column=4, padx=2, pady=2, sticky=tk.W)
        tk.Checkbutton(query_Frame, text='图像集合', variable=self.Images).grid(row=2, column=1, padx=2, pady=2, sticky=tk.W)
        tk.Checkbutton(query_Frame, text='文件', variable=self.Files).grid(row=2, column=2, padx=2, pady=2, sticky=tk.W)
        tk.Checkbutton(query_Frame, text='视频片段', variable=self.VideoSlices).grid(row=2, column=3, padx=2, pady=2, sticky=tk.W)   
        self.selectAllBtn = tk.Button(query_Frame, text="全选", width=10, command=self.selectAll)
        self.selectAllBtn.grid(row=2, column=4, padx=2, pady=2, sticky=tk.W)          
        #self.posttype = ""        
        #tk.Entry(query_Frame, textvariable=self.posttype, width=60).grid(row=1, column=1, padx=2, pady=2, columnspan=5, stick=tk.W)
        #tk.Label(query_Frame, text='图片类型:').grid(row=1, column=2, padx=2, pady=2, stick=tk.W)        
        #self.pictype = tk.StringVar()
        #self.pictype.set("场景;")
        #tk.Entry(query_Frame, textvariable=self.pictype, width=15).grid(row=1, column=3, padx=2, pady=2, stick=tk.W)
        
        tk.Label(query_Frame, text='前端IP:').grid(row=3, column=0, padx=2, pady=2, stick=tk.W)        
        self.deviceip = tk.StringVar()
        self.deviceip.set("")
        tk.Entry(query_Frame, textvariable=self.deviceip, width=20).grid(row=3, column=1, padx=2, pady=2, columnspan=5, stick=tk.W)
        self.queryBtn = tk.Button(query_Frame, text='查询', width=10, command=self.query)
        self.queryBtn.grid(row=3, column=3, padx=2, pady=2, sticky=tk.W)
        
        tk.Button(query_Frame, text='打开多个文件', command=self.openfiles).grid(row=4, column=0, padx=2, pady=2, stick=tk.W)   
        self.jsonfiles = tk.StringVar()
        self.jsonfiles.set("")
        self.alljsonfiles=()
        tk.Entry(query_Frame, textvariable=self.jsonfiles, width=20).grid(row=4, column=1, padx=2, pady=2, columnspan=5, stick=tk.W)
        self.parsejsonBtn = tk.Button(query_Frame, text='解析GAjson', width=10, command=self.parsejson)
        self.parsejsonBtn.grid(row=4, column=3, padx=2, pady=2, sticky=tk.W)
        self.parsekeyBtn = tk.Button(query_Frame, text='解析键值', width=10, command=self.parsekey)
        self.parsekeyBtn.grid(row=4, column=4, padx=2, pady=2, sticky=tk.W)
               
        # 清除
        tk.Button(query_Frame, text="清除", width=10, command=self.clearresult).grid(row=5, column=0, padx=2, pady=2, stick=tk.W)                       
        tk.Button(query_Frame, text="保存", width=10, command=self.saveresult).grid(row=5, column=1, padx=2, pady=2, stick=tk.W)                        
        self.result_Text = tk.Text(query_Frame, width=70, height=25, wrap='none')  
        self.result_Text.grid(row=6, column=0, padx=2, pady=2, rowspan=2, columnspan=5, sticky='W')  
        
        self.result_scrollbar_y = tk.Scrollbar(query_Frame)                         #创建纵向滚动条
        self.result_scrollbar_y.config(command=self.result_Text.yview)      
        #将创建的滚动条通过command参数绑定到需要拖动的Text上
        self.result_Text.config(yscrollcommand=self.result_scrollbar_y.set)   #Text反向绑定滚动条
        self.result_scrollbar_y.grid(row=6, column=5, rowspan=2, columnspan=5, sticky='ESN')  
                
        self.result_scrollbar_x = tk.Scrollbar(query_Frame, orient=tk.HORIZONTAL)     #创建横向滚动条
        self.result_scrollbar_x.config(command=self.result_Text.xview)  
        #将创建的滚动条通过command参数绑定到需要拖动的Text上
        self.result_Text.config(xscrollcommand=self.result_scrollbar_x.set)   #Text反向绑定滚动条
        self.result_scrollbar_x.grid(row=8, column=0, rowspan=2, columnspan=5, sticky='EW')  
    
    def init_Window_CTCP(self):
        set_Frame = tk.LabelFrame(self, text='CTCP设置', padx=2, pady=2)
        set_Frame.grid(row=1, column=0, padx=5, pady=5, stick=tk.W)
        
        tk.Label(set_Frame, text='Server IP:').grid(row=0, column=0, padx=2, pady=2, stick=tk.W)        
        self.ctcp_serverip = tk.StringVar()
        self.ctcp_serverip.set("")
        self.entry_ctcp_serverip = tk.Entry(set_Frame, textvariable=self.ctcp_serverip, width=20)
        self.entry_ctcp_serverip.grid(row=0, column=1, padx=2, pady=2, stick=tk.W)
        tk.Label(set_Frame, text='Server Port:').grid(row=1, column=0, padx=2, pady=2, stick=tk.W)        
        self.ctcp_serverport = tk.IntVar()
        self.ctcp_serverport.set(9999)
        self.entry_ctcp_serverport = tk.Entry(set_Frame, textvariable=self.ctcp_serverport, width=20)
        self.entry_ctcp_serverport.grid(row=1, column=1, padx=2, pady=2, stick=tk.W)                        
        self.ctcp_startBtn = tk.Button(set_Frame, text='启用CTCP', width=10, command=self.ctcp_run)
        self.ctcp_startBtn.grid(row=2, column=0, padx=2, pady=2,sticky=tk.W)
        tk.Button(set_Frame, text='说明', width=10, command=self.ctcp_about).grid(row=2, column=1, padx=2, pady=2,sticky=tk.W)
        
        self.ctcp_save_jpg = tk.IntVar()
        self.ctcp_cb_savejpg = tk.Checkbutton(set_Frame, text='保存图片', variable=self.ctcp_save_jpg)
        self.ctcp_cb_savejpg.grid(row=0, column=2, padx=2, pady=2, sticky=tk.W)
        self.ctcp_check_jpg = tk.IntVar()
        self.ctcp_cb_checkjpg = tk.Checkbutton(set_Frame, text='判断图片格式', variable=self.ctcp_check_jpg)
        self.ctcp_cb_checkjpg.grid(row=0, column=3, padx=2, pady=2, sticky=tk.W)
        self.ctcp_save_cpssbin = tk.IntVar()
        self.ctcp_cb_save_cpssbin = tk.Checkbutton(set_Frame, text='保存完整数据', variable=self.ctcp_save_cpssbin)
        self.ctcp_cb_save_cpssbin.grid(row=1, column=2, padx=2, pady=2, sticky=tk.W)
        self.ctcp_loglevel = tk.IntVar()
        self.ctcp_cb_loglevel = tk.Checkbutton(set_Frame, text='更多打印信息', variable=self.ctcp_loglevel)
        self.ctcp_cb_loglevel.grid(row=1, column=3, padx=2, pady=2, sticky=tk.W)        
        self.ctcp_errcode = tk.IntVar()
        self.ctcp_cb_errcode = tk.Checkbutton(set_Frame, text='返回结果码(0-9):', variable=self.ctcp_errcode)
        self.ctcp_cb_errcode.grid(row=2, column=2, padx=2, pady=2, sticky=tk.W)
        self.ctcp_err = tk.IntVar()
        self.ctcp_err.set(0)
        self.ctcp_errEntry = tk.Entry(set_Frame, textvariable=self.ctcp_err, width=5)
        self.ctcp_errEntry.grid(row=2, column=3, padx=2, pady=2, sticky=tk.W) 
        self.ctcp_noparseID = tk.IntVar()
        self.ctcp_cb_noparseID = tk.Checkbutton(set_Frame, text='不解析消息直接返回成功', variable=self.ctcp_noparseID)
        self.ctcp_cb_noparseID.grid(row=3, column=2, padx=2, pady=2, sticky=tk.W)        
    
    def init_Window_GA(self):
        set_Frame = tk.LabelFrame(self, text='GA1400设置', padx=2, pady=2)
        set_Frame.grid(row=2, column=0, padx=5, pady=5, stick=tk.W)
        
        tk.Label(set_Frame, text='Server IP:').grid(row=0, column=0, padx=2, pady=2, stick=tk.W)        
        self.ga_serverip = tk.StringVar()
        self.ga_serverip.set("")
        self.entry_gaserverip = tk.Entry(set_Frame, textvariable=self.ga_serverip, width=20)
        self.entry_gaserverip.grid(row=0, column=1, padx=2, pady=2, stick=tk.W)
        tk.Label(set_Frame, text='Server Port:').grid(row=1, column=0, padx=2, pady=2, stick=tk.W)        
        self.ga_serverport = tk.IntVar()
        self.ga_serverport.set(8080)
        self.entry_gaport = tk.Entry(set_Frame, textvariable=self.ga_serverport, width=20)
        self.entry_gaport.grid(row=1, column=1, padx=2, pady=2, stick=tk.W)                        
        tk.Label(set_Frame, text='https Port:').grid(row=2, column=0, padx=2, pady=2, stick=tk.W)        
        self.ga_httpsport = tk.IntVar()
        self.ga_httpsport.set(8081)
        self.entry_gahttpsport = tk.Entry(set_Frame, textvariable=self.ga_httpsport, width=20)
        self.entry_gahttpsport.grid(row=2, column=1, padx=2, pady=2, stick=tk.W)                        
        self.ga_startBtn = tk.Button(set_Frame, text='启用GA1400', width=10, command=self.ga_run)
        self.ga_startBtn.grid(row=3, column=0, padx=2, pady=2,sticky=tk.W)
        self.gahttps_startBtn = tk.Button(set_Frame, text='启用GA1400(https)', width=15, command=self.gahttps_run)
        self.gahttps_startBtn.grid(row=3, column=1, padx=2, pady=2,sticky=tk.W)
        tk.Button(set_Frame, text='说明', width=10, command=self.ga_about).grid(row=4, column=1, padx=2, pady=2,sticky=tk.W)
        
        self.ga_save_jpg = tk.IntVar()
        self.ga_cb_savejpg = tk.Checkbutton(set_Frame, text='保存图片', variable=self.ga_save_jpg)
        self.ga_cb_savejpg.grid(row=0, column=2, padx=2, pady=2, sticky=tk.W)
        self.ga_check_jpg = tk.IntVar()
        self.ga_cb_checkjpg = tk.Checkbutton(set_Frame, text='判断图片格式', variable=self.ga_check_jpg)
        self.ga_cb_checkjpg.grid(row=0, column=3, padx=2, pady=2, sticky=tk.W)
        self.ga_show_registertime = tk.IntVar()
        self.ga_cb_showregtime = tk.Checkbutton(set_Frame, text='查看注册时间', variable=self.ga_show_registertime)
        self.ga_cb_showregtime.grid(row=1, column=2, padx=2, pady=2, sticky=tk.W)
        self.ga_check_auth = tk.IntVar()
        self.ga_cb_checkauth = tk.Checkbutton(set_Frame, text='携带授权信息', variable=self.ga_check_auth)
        self.ga_cb_checkauth.grid(row=1, column=3, padx=2, pady=2, sticky=tk.W)
        self.ga_noparseID = tk.IntVar()
        self.ga_cb_noparseID = tk.Checkbutton(set_Frame, text='不解析消息直接返回成功', variable=self.ga_noparseID)
        self.ga_cb_noparseID.grid(row=2, column=2, padx=2, pady=2, sticky=tk.W)
        self.ga_save_json = tk.IntVar()
        self.ga_cb_savejson = tk.Checkbutton(set_Frame, text='保存json', variable=self.ga_save_json)
        self.ga_cb_savejson.grid(row=2, column=3, padx=2, pady=2, sticky=tk.W)
        self.ga_usegaini = tk.IntVar()
        self.ga_cb_usegaini = tk.Checkbutton(set_Frame, text='使用ga.ini', variable=self.ga_usegaini)
        self.ga_cb_usegaini.grid(row=3, column=2, padx=2, pady=2, sticky=tk.W)
        self.ga_loglevel = tk.IntVar()
        self.ga_cb_loglevel = tk.Checkbutton(set_Frame, text='更多log信息', variable=self.ga_loglevel)
        self.ga_cb_loglevel.grid(row=3, column=3, padx=2, pady=2, sticky=tk.W)
        self.ga_updateRegister = tk.IntVar()
        self.ga_cb_updateRegister = tk.Checkbutton(set_Frame, text='刷新注册', variable=self.ga_updateRegister)
        self.ga_cb_updateRegister.grid(row=4, column=2, padx=2, pady=2, sticky=tk.W)
        self.ga_use_sqlite3 = tk.IntVar()
        self.ga_cb_use_sqlite3 = tk.Checkbutton(set_Frame, text='保存入库', variable=self.ga_use_sqlite3)
        self.ga_cb_use_sqlite3.grid(row=4, column=3, padx=2, pady=2, sticky=tk.W)
       
    def init_Window_HIK(self):
        set_Frame = tk.LabelFrame(self, text='HIK设置', padx=2, pady=2)
        set_Frame.grid(row=3, column=0, padx=5, pady=5, stick=tk.W)    
        
        tk.Label(set_Frame, text='Server IP:').grid(row=0, column=0, padx=2, pady=2, stick=tk.W)        
        self.hik_serverip = tk.StringVar()
        self.hik_serverip.set("")
        self.entry_hik_serverip = tk.Entry(set_Frame, textvariable=self.hik_serverip, width=20)
        self.entry_hik_serverip.grid(row=0, column=1, padx=2, pady=2, stick=tk.W)
        tk.Label(set_Frame, text='Server Port:').grid(row=1, column=0, padx=2, pady=2, stick=tk.W)        
        self.hik_serverport = tk.IntVar()
        self.hik_serverport.set(8082)
        self.entry_hik_serverport = tk.Entry(set_Frame, textvariable=self.hik_serverport, width=20)
        self.entry_hik_serverport.grid(row=1, column=1, padx=2, pady=2, stick=tk.W)                        
        self.hik_startBtn = tk.Button(set_Frame, text='启用HIK', width=10, command=self.hik_run)
        self.hik_startBtn.grid(row=2, column=0, padx=2, pady=2,sticky=tk.W)
        tk.Button(set_Frame, text='说明', width=10, command=self.hik_about).grid(row=2, column=1, padx=2, pady=2,sticky=tk.W)
        
        self.hik_save_jpg = tk.IntVar()
        self.hik_cb_savejpg = tk.Checkbutton(set_Frame, text='保存图片', variable=self.hik_save_jpg)
        self.hik_cb_savejpg.grid(row=0, column=2, padx=2, pady=2, sticky=tk.W)
        self.hik_check_jpg = tk.IntVar()
        self.hik_cb_checkjpg = tk.Checkbutton(set_Frame, text='判断图片格式', variable=self.hik_check_jpg)
        self.hik_cb_checkjpg.grid(row=0, column=3, padx=2, pady=2, sticky=tk.W)
        self.hik_save_cpssbin = tk.IntVar()
        self.hik_cb_save_cpssbin = tk.Checkbutton(set_Frame, text='保存完整数据', variable=self.hik_save_cpssbin)
        #self.hik_cb_save_cpssbin.grid(row=1, column=2, padx=2, pady=2, sticky=tk.W)
        self.hik_loglevel = tk.IntVar()
        self.hik_cb_loglevel = tk.Checkbutton(set_Frame, text='更多打印信息', variable=self.hik_loglevel)
        self.hik_cb_loglevel.grid(row=1, column=3, padx=2, pady=2, sticky=tk.W)        
        
        self.hik_noparseID = tk.IntVar()
        self.hik_cb_noparseID = tk.Checkbutton(set_Frame, text='不解析消息直接返回成功', variable=self.hik_noparseID)
        self.hik_cb_noparseID.grid(row=1, column=2, padx=2, pady=2, sticky=tk.W)  
        
    def selectAll(self):
        # 点击 “全选” 按钮功能               
        if self.selectAllBtn['text'] == '全选':
            self.selectAllBtn['text'] = '反选'
            self.Faces.set(1)
            self.Persons.set(1)
            self.MotorVehicles.set(1)
            self.NonMotorVehicles.set(1)
            self.Images.set(1)
            self.Files.set(1)
            self.VideoSlices.set(1)     
        else:
            self.selectAllBtn['text'] = '全选'
            self.Faces.set(0)
            self.Persons.set(0)
            self.MotorVehicles.set(0)
            self.NonMotorVehicles.set(0)
            self.Images.set(0)
            self.Files.set(0)
            self.VideoSlices.set(0)     
    
    def clearresult(self):
        self.result_Text.delete(1.0, tk.END)  
        
    def saveresult(self):  
        #result_filename = "result_%s.log"%(time.strftime("%Y%m%d_%H%M%S", time.localtime(time.time())))
        result_filename = "result.log"
        self.result_Text.insert(tk.END, "保存到 %s"%result_filename + '\n') 
        self.result_Text.see(tk.END)        
        msg = self.result_Text.get(1.0, tk.END)
        with open(result_filename, 'w') as f:
            f.write(msg)
        
    def ctcp_about(self):  
        ctcpmsg = "ctcp server version is {}\n".format(tcp_cpss_v2.VERSION) 
        ctcpmsg += "password is 12345678\n"
        ctcpmsg += '"Keep AlivePeriod":10s\n' 
        ctcpmsg += "\n"
        ctcpmsg += "图片和log存放目录: ./ctcp/\n"
        ctcpmsg += "图片命名：face_faceSetId_ShotTime_数字.jpg, motor_MotorVehicleID_PassTime_ShotTime_数字.jpg\n"
        ctcpmsg += "\n"
        ctcpmsg += "勾选【保存图片】：保存jpg图片\n"
        ctcpmsg += "勾选【判断图片格式】：当jpg格式错误返回错误信息给前端（不勾选只检查jpg格式，不会返回错误）\n"
        ctcpmsg += "勾选【保存完整数据】：保存接收文件为二进制bin文件\n"
        ctcpmsg += "勾选【更多打印信息】：显示更多打印消息\n"
        ctcpmsg += "勾选【返回结果码】：0表示正确结果码, 1-9是当接收图片后回复前端错误的结果码\n"
        ctcpmsg += "勾选【不解析消息直接返回成功】：只接收消息，不解析内容直接返回成功\n"        
        showinfo(title='CTCP', message=ctcpmsg)  
        
    def ga_about(self):  
        gamsg = """图片：ip_PersonID_ImageID_Shottime_PersonObject_场景图.jpg
        ip_ImageID_Shottime_Image.jpg
        ip_FileID_FileName
        ip_VideoID_Begintime_Endtime.ps"""
        gamsg += "\n"
        gamsg += "勾选【保存图片】：保存jpg图片\n"
        gamsg += "勾选【判断图片格式】：当jpg格式错误返回错误信息给前端（不勾选只检查jpg格式，不会返回错误）\n"
        gamsg += "勾选【查看注册时间】：打印消息中显示前端注册时间\n"
        gamsg += "勾选【携带授权信息】：每个消息都携带Authorization\n"
        gamsg += "勾选【不解析消息直接返回成功】：只接收消息，不解析内容直接返回成功\n"
        gamsg += "勾选【保存json】：保存json数据\n"
        gamsg += "勾选【使用ga.ini】：使用ga.ini的配置响应http请求\n"
        gamsg += "勾选【刷新注册】：服务器间隔1小时向前端发送401，要求前端刷新注册\n"
        gamsg += "勾选【保存入库】：保存人脸，车辆等属性到gahttp_时间.db\n"
        showinfo(title='GA1400', message=gamsg)      
        
    def hik_about(self):   
        hikmsg = "hik server version is {}\n".format(http_Hik_v2.VERSION) 
        hikmsg += "图片和log存放目录: ./hik/\n"
        hikmsg += "\n"
        hikmsg += "图片命名：filename\n"
        hikmsg += "文件命名：zptime.txt\n"
        hikmsg += "\n"
        hikmsg += "勾选【保存图片】：保存jpg图片\n"
        hikmsg += "勾选【判断图片格式】：当jpg格式错误返回错误信息给前端（不勾选只检查jpg格式，不会返回错误）\n"
        hikmsg += "勾选【不解析消息直接返回成功】：只接收消息，不解析内容直接返回成功\n"
        showinfo(title='Hik', message=hikmsg)      
        
    def ctcp_run(self):
        if self.ctcp_t.is_alive():
            self.ctcp.stop()
            return                    
        self.ctcp_t = threading.Thread(target=self.ctcp_run_thread, name='ctcp_run_thread')
        self.ctcp_t.daemon = True
        self.ctcp_t.start()
                          
    def ctcp_run_thread(self):
        self.ctcp_startBtn['text'] = '停止CTCP'  
        # 1, 初始化
        tcp_cpss_v2.save_jpg = self.ctcp_save_jpg.get()
        tcp_cpss_v2.save_cpssbin = self.ctcp_save_cpssbin.get()
        tcp_cpss_v2.check_jpg = self.ctcp_check_jpg.get()
        tcp_cpss_v2.LOG = self.ctcp_loglevel.get()        
        tcp_cpss_v2.noresponse = self.ctcp_noparseID.get()
        if self.ctcp_errcode.get():
            try:
                tcp_cpss_v2.result_code_err = self.ctcp_err.get()
            except:
                pass
        self.ctcp_cb_savejpg['state'] = 'disabled'
        self.ctcp_cb_save_cpssbin['state'] = 'disabled'
        self.ctcp_cb_checkjpg['state'] = 'disabled'
        self.ctcp_cb_errcode['state'] = 'disabled'
        self.ctcp_errEntry['state'] = 'disabled'
        self.ctcp_cb_loglevel['state'] = 'disabled'
        self.ctcp_cb_noparseID['state'] = 'disabled'
        self.entry_ctcp_serverip['state'] = 'disabled'
        self.entry_ctcp_serverport['state'] = 'disabled'
        # 2， 启动
        self.ctcp.run(self.ctcp_serverip.get(), self.ctcp_serverport.get())  
        self.ctcp_cb_savejpg['state'] = 'normal'
        self.ctcp_cb_save_cpssbin['state'] = 'normal'
        self.ctcp_cb_checkjpg['state'] = 'normal'
        self.ctcp_cb_errcode['state'] = 'normal'
        self.ctcp_errEntry['state'] = 'normal'
        self.ctcp_cb_loglevel['state'] = 'normal'
        self.ctcp_cb_noparseID['state'] = 'normal' 
        self.entry_ctcp_serverip['state'] = 'normal'
        self.entry_ctcp_serverport['state'] = 'normal'
        self.ctcp_startBtn['text'] = '启用CTCP'  
        print_tofile('退出线程', threading.current_thread().name) 
			    
    def hik_run(self):
        if self.hik_t.is_alive():
            self.hik.stop()
            return                    
        self.hik_t = threading.Thread(target=self.hik_run_thread, name='hik_run_thread')
        self.hik_t.daemon = True
        self.hik_t.start()
       
    def hik_run_thread(self):
        self.hik_startBtn['text'] = '停止HIK'  
        # 1, 初始化
        http_Hik_v2.save_jpg = self.hik_save_jpg.get()
        http_Hik_v2.check_jpg = self.hik_check_jpg.get()
        http_Hik_v2.noresponse = self.hik_noparseID.get()
        http_Hik_v2.loglevel = self.hik_loglevel.get()

        self.hik_cb_savejpg['state'] = 'disabled'
        self.hik_cb_checkjpg['state'] = 'disabled'
        self.hik_cb_loglevel['state'] = 'disabled'
        self.hik_cb_noparseID['state'] = 'disabled'
        self.entry_hik_serverip['state'] = 'disabled'
        self.entry_hik_serverport['state'] = 'disabled'
        # 2， 启动
        self.hik.run(self.hik_serverip.get(), self.hik_serverport.get())  
        self.hik_cb_savejpg['state'] = 'normal'
        self.hik_cb_checkjpg['state'] = 'normal'
        self.hik_cb_loglevel['state'] = 'normal'
        self.hik_cb_noparseID['state'] = 'normal' 
        self.entry_hik_serverip['state'] = 'normal'
        self.entry_hik_serverport['state'] = 'normal'
        self.hik_startBtn['text'] = '启用HIK'  
        print_tofile('退出线程', threading.current_thread().name) 
    
    def ga_run(self):
        if self.ga_t.isAlive():
            self.ga.stop()
            return                    
        self.ga_t = threading.Thread(target=self.ga_run_thread, name='ga_run_thread')
        self.ga_t.daemon = True
        self.ga_t.start() 
        
    def gahttps_run(self):
        if self.gahttps_t.isAlive():
            self.gahttps.stop()
            return            
        self.gahttps_t = threading.Thread(target=self.gahttps_run_thread, name='gahttps_run_thread')
        self.gahttps_t.daemon = True
        self.gahttps_t.start()
            
    def ga_run_thread(self):
        self.ga_startBtn['text'] = '停止GA1400'  
        # 1, 初始化
        http_GA_v2.save_jpg = self.ga_save_jpg.get()
        http_GA_v2.save_json = self.ga_save_json.get()
        http_GA_v2.show_registertime = self.ga_show_registertime.get()
        http_GA_v2.check_jpg = self.ga_check_jpg.get()
        http_GA_v2.check_auth = self.ga_check_auth.get()
        http_GA_v2.loglevel = self.ga_loglevel.get()
        http_GA_v2.noparseID = self.ga_noparseID.get()
        http_GA_v2.usegaini = self.ga_usegaini.get()        
        http_GA_v2.updateRegister = self.ga_updateRegister.get()  
        http_GA_v2.use_sqlite3 = self.ga_use_sqlite3.get()
        
        self.ga_cb_savejpg['state'] = 'disabled'
        self.ga_cb_savejson['state'] = 'disabled'
        self.ga_cb_showregtime['state'] = 'disabled'
        self.ga_cb_checkjpg['state'] = 'disabled'
        self.ga_cb_checkauth['state'] = 'disabled'
        self.ga_cb_loglevel['state'] = 'disabled'
        self.ga_cb_noparseID['state'] = 'disabled'
        self.ga_cb_usegaini['state'] = 'disabled'
        self.ga_cb_updateRegister['state'] = 'disabled'    
        self.ga_cb_use_sqlite3['state'] = 'disabled'    
        self.entry_gaport['state'] = 'disabled'
        # 2， 启动
        self.ga.run(self.ga_serverip.get(), self.ga_serverport.get())   
        self.ga_cb_savejpg['state'] = 'normal'
        self.ga_cb_savejson['state'] = 'normal'
        self.ga_cb_showregtime['state'] = 'normal'
        self.ga_cb_checkjpg['state'] = 'normal'
        self.ga_cb_checkauth['state'] = 'normal'
        self.ga_cb_loglevel['state'] = 'normal'
        self.ga_cb_noparseID['state'] = 'normal'
        self.ga_cb_usegaini['state'] = 'normal' 
        self.ga_cb_updateRegister['state'] = 'normal'    
        self.ga_cb_use_sqlite3['state'] = 'normal'      
        self.entry_gaport['state'] = 'normal'  
        self.ga_startBtn['text'] = '启用GA1400'  
        print_tofile('退出线程', threading.current_thread().name) 
             
    def gahttps_run_thread(self):
        self.gahttps_startBtn['text'] = '停止GA1400(https)'  
        # 1, 初始化
        https_GA.save_jpg = self.ga_save_jpg.get()
        https_GA.save_json = self.ga_save_json.get()
        https_GA.show_registertime = self.ga_show_registertime.get()
        https_GA.check_jpg = self.ga_check_jpg.get()
        https_GA.check_auth = self.ga_check_auth.get()
        https_GA.loglevel = self.ga_loglevel.get()
        https_GA.noparseID = self.ga_noparseID.get()
        https_GA.usegaini = self.ga_usegaini.get()
        https_GA.updateRegister = self.ga_updateRegister.get()  
        https_GA.use_sqlite3 = self.ga_use_sqlite3.get()
       
        self.ga_cb_savejpg['state'] = 'disabled'
        self.ga_cb_savejson['state'] = 'disabled'
        self.ga_cb_showregtime['state'] = 'disabled'
        self.ga_cb_checkjpg['state'] = 'disabled'
        self.ga_cb_checkauth['state'] = 'disabled'
        self.ga_cb_loglevel['state'] = 'disabled'
        self.ga_cb_noparseID['state'] = 'disabled' 
        self.ga_cb_usegaini['state'] = 'disabled'  
        self.ga_cb_updateRegister['state'] = 'disabled'    
        self.ga_cb_use_sqlite3['state'] = 'disabled'    
        self.entry_gahttpsport['state'] = 'disabled'   
        # 2， 启动
        self.gahttps.run(self.ga_serverip.get(), self.ga_httpsport.get())  
        self.ga_cb_savejpg['state'] = 'normal'
        self.ga_cb_savejson['state'] = 'normal'
        self.ga_cb_showregtime['state'] = 'normal'
        self.ga_cb_checkjpg['state'] = 'normal'
        self.ga_cb_checkauth['state'] = 'normal'
        self.ga_cb_loglevel['state'] = 'normal'
        self.ga_cb_noparseID['state'] = 'normal'
        self.ga_cb_usegaini['state'] = 'normal'    
        self.ga_cb_updateRegister['state'] = 'normal'     
        self.ga_cb_use_sqlite3['state'] = 'normal'    
        self.entry_gahttpsport['state'] = 'normal'   
        self.gahttps_startBtn['text'] = '启用GA1400(https)'  
        print_tofile('退出线程', threading.current_thread().name) 
        
    def query(self):
        if self.query_t.is_alive():
            self._running.clear()
            #showinfo(title='提示', message="线程 “{}” 还未退出，请稍候...".format(self.ctcp_t.getName()))
            return                    
        self.query_t = threading.Thread(target=self.query_thread, name='query_thread')
        self.query_t.daemon = True
        self._running.set()
        self.query_t.start()
                  
    def query_thread(self):
        self.queryBtn['text'] = '查询...'  
        msg = ''
        if self.q_CTCP.get():
            msg += '*'*20 + ' CTCP ' + '*'*30 + '\n' 
            msg += tcp_cpss_v2.fetch_device(self.deviceip.get())
            msg += '*'*50 + '\n' + '\n'
        if self.q_GA1400.get():
            msg += '*'*20 + ' GA1400 ' + '*'*30 + '\n'        
            #posttype = "Faces;Persons;MotorVehicles;NonMotorVehicles;Images;Files;VideoSlices"
            posttype= ''
            if self.Faces.get():
                posttype +='Faces;'
            if self.Persons.get():
                posttype +='Persons;'
            if self.MotorVehicles.get():
                posttype +='MotorVehicles;'
            if self.NonMotorVehicles.get():
                posttype +='NonMotorVehicles;'
            if self.Images.get():
                posttype +='Images;'
            if self.Files.get():
                posttype +='Files;'
            if self.VideoSlices.get():
                posttype +='VideoSlices;'
            msg += 'GA1400(http port={})\n'.format(self.ga_serverport.get())
            msg += http_GA_v2.fetch_device(self.deviceip.get(), posttype)
            msg += '*'*20 + '\n'
            msg += 'GA1400(https port={})\n'.format(self.ga_httpsport.get())
            msg += https_GA.fetch_device(self.deviceip.get(), posttype)
            msg += '*'*50 + '\n' + '\n'
        if self.q_HIK.get():
            msg += '*'*20 + ' HIK ' + '*'*30 + '\n'
            msg += http_Hik_v2.fetch_device(self.deviceip.get())
            msg += '*'*50 + '\n' + '\n'
        if len(msg)>0:            
            self.result_Text.insert(tk.END, msg)
            self.result_Text.see(tk.END) 
        self.queryBtn['text'] = '查询'  
        print_tofile('退出线程', threading.current_thread().name) 

    def openfiles(self):        
        #files = filedialog.askopenfilenames(title='打开文件',filetypes=[('file', '*.json'), ('All Files', '*.*')], initialdir=(os.path.abspath("D:/")) )
        files = filedialog.askopenfilenames(title='打开文件',filetypes=[('file', '*.json'), ('All Files', '*.*')])
        if files:
            self.alljsonfiles = files
            if len(files)>5:
                self.jsonfiles.set(files[0]+';… 共%d个文件'%len(files))
            else:
                self.jsonfiles.set(';'.join(files))
    
    def parsejson(self):
        if self.parse_t.is_alive():
            return                   
        self.parse_t = threading.Thread(target=self.parse_thread, args=(0,),name='parse_thread')
        self.parse_t.daemon = True
        self.parse_t.start()
                  
    def parse_thread(self,sel):
        if self.alljsonfiles:
            if sel == 0:
                text = self.parsejsonBtn['text'] 
                self.parsejsonBtn['text'] = text + '...'  
                for file in self.alljsonfiles:
                    try:
                        ret = '' 
                        with open(file, 'r', encoding='utf8') as f: 
                            json_dict = json.loads(f.read())  
                            if isinstance(json_dict, dict):
                                ret += get_jsonkeys.get_face(json_dict) 
                                ret += get_jsonkeys.get_person(json_dict) 
                                ret += get_jsonkeys.get_MotorVehicle(json_dict) 
                                ret += get_jsonkeys.get_NonMotorVehicle(json_dict) 
                                ret += get_jsonkeys.get_file(json_dict) 
                                ret += get_jsonkeys.get_image(json_dict) 
                                ret += get_jsonkeys.get_video(json_dict) 
                            else:
                                self.result_Text.insert(tk.END, file + ' is not dict\n')  
                                self.result_Text.see(tk.END)                                         
                    except Exception as e:
                        self.result_Text.insert(tk.END, file + ' ' + str(e) + '\n')  
                        self.result_Text.see(tk.END) 
                    else:
                        if len(ret)>0:         
                            self.result_Text.insert(tk.END, file + '\n')        
                            self.result_Text.insert(tk.END, ret)
                            self.result_Text.see(tk.END)         
                self.parsejsonBtn['text'] = text
            else:  
                text = self.parsekeyBtn['text'] 
                self.parsekeyBtn['text'] = text + '...'                     
                for file in self.alljsonfiles:
                    try:
                        ret = '' 
                        with open(file, 'r', encoding='utf8') as f: 
                            json_dict = json.loads(f.read())  
                            if isinstance(json_dict, dict):
                                traverse_json.result_json.clear()    
                                traverse_json.get_jsonkey(json_dict) 
                                for x in traverse_json.result_json:
                                    ret += x + '\n'
                            else:
                                self.result_Text.insert(tk.END, file + ' is not dict\n')  
                                self.result_Text.see(tk.END)                           
                    except Exception as e:
                        self.result_Text.insert(tk.END, file + ' ' + str(e) + '\n')  
                        self.result_Text.see(tk.END) 
                    else:
                        if len(ret)>0:            
                            self.result_Text.insert(tk.END, file + '\n')
                            self.result_Text.insert(tk.END, ret)
                            self.result_Text.see(tk.END) 
                self.parsekeyBtn['text'] = text 
            
    def parsekey(self):
        if self.parse_t.is_alive():
            return                   
        self.parse_t = threading.Thread(target=self.parse_thread, args=(1,),name='parse_thread')
        self.parse_t.daemon = True
        self.parse_t.start()

if __name__ == '__main__':    
    root = tk.Tk()
    root.title("GA/CTCP/HIK Server " + tkVERSION)
    root.geometry("1100x660+200+50")
    root.resizable(0,0)
    frame = PageOne(root, root)
    frame.grid(row=0, column=0, padx=2, pady=2, sticky="nsew")         
    frame.tkraise()
    root.mainloop()
    
